/**
 * 文件功能：API请求相关的React Hooks
 * 作者：开发者
 * 日期：2024年
 * 描述：提供便于在React组件中使用的API请求Hooks
 */

import { useState, useEffect, useCallback } from 'react';
import ApiService from './index';

/**
 * 通用API请求Hook
 * @param {Function} apiFunction - API请求函数
 * @param {Array} dependencies - 依赖数组，当依赖变化时重新请求
 * @param {boolean} immediate - 是否立即执行请求
 * @returns {Object} 包含数据、加载状态、错误信息和重新请求函数的对象
 */
export const useApi = (apiFunction, dependencies = [], immediate = true) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  /**
   * 执行API请求
   * @param {...any} args - 传递给API函数的参数
   */
  const execute = useCallback(async (...args) => {
    try {
      setLoading(true);
      setError(null);
      const result = await apiFunction(...args);
      setData(result);
      return result;
    } catch (err) {
      setError(err.message || '请求失败');
      throw err;
    } finally {
      setLoading(false);
    }
  }, [apiFunction]);

  useEffect(() => {
    if (immediate) {
      execute();
    }
  }, dependencies);

  return {
    data,
    loading,
    error,
    execute,
    refetch: execute,
  };
};

/**
 * 用户登录Hook
 * @returns {Object} 登录相关的状态和方法
 */
export const useLogin = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  /**
   * 执行登录
   * @param {Object} loginData - 登录数据
   * @param {string} loginData.username - 用户名
   * @param {string} loginData.password - 密码
   * @returns {Promise} 登录结果
   */
  const login = useCallback(async (loginData) => {
    try {
      setLoading(true);
      setError(null);
      const result = await ApiService.user.login(loginData);
      
      // 保存token到localStorage
      if (result.token) {
        localStorage.setItem('token', result.token);
      }
      
      return result;
    } catch (err) {
      setError(err.message || '登录失败');
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * 执行登出
   */
  const logout = useCallback(async () => {
    try {
      setLoading(true);
      await ApiService.user.logout();
      localStorage.removeItem('token');
    } catch (err) {
      console.error('登出失败:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    login,
    logout,
    loading,
    error,
  };
};

/**
 * 文件上传Hook
 * @returns {Object} 文件上传相关的状态和方法
 */
export const useFileUpload = () => {
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState(null);

  /**
   * 上传文件
   * @param {File} file - 要上传的文件
   * @param {Function} onProgress - 进度回调函数
   * @returns {Promise} 上传结果
   */
  const upload = useCallback(async (file, onProgress) => {
    try {
      setUploading(true);
      setError(null);
      setProgress(0);

      const formData = new FormData();
      formData.append('file', file);

      const result = await ApiService.file.upload(formData);
      setProgress(100);
      return result;
    } catch (err) {
      setError(err.message || '上传失败');
      throw err;
    } finally {
      setUploading(false);
    }
  }, []);

  return {
    upload,
    uploading,
    progress,
    error,
  };
};

/**
 * 分页数据Hook
 * @param {Function} apiFunction - 获取分页数据的API函数
 * @param {Object} initialParams - 初始查询参数
 * @returns {Object} 分页数据相关的状态和方法
 */
export const usePagination = (apiFunction, initialParams = {}) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    ...initialParams,
  });

  /**
   * 获取数据
   * @param {Object} params - 查询参数
   */
  const fetchData = useCallback(async (params = {}) => {
    try {
      setLoading(true);
      setError(null);
      
      const queryParams = {
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...params,
      };
      
      const result = await apiFunction(queryParams);
      
      setData(result.list || result.data || []);
      setPagination(prev => ({
        ...prev,
        total: result.total || 0,
      }));
      
      return result;
    } catch (err) {
      setError(err.message || '获取数据失败');
      throw err;
    } finally {
      setLoading(false);
    }
  }, [apiFunction, pagination.current, pagination.pageSize]);

  /**
   * 改变页码
   * @param {number} page - 页码
   * @param {number} pageSize - 每页数量
   */
  const onChange = useCallback((page, pageSize) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize: pageSize || prev.pageSize,
    }));
  }, []);

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize]);

  return {
    data,
    loading,
    error,
    pagination,
    fetchData,
    onChange,
    refresh: () => fetchData(),
  };
};